package logic

import (
	"context"
	"errors"
	"shuqi-novel/mysql"

	"shuqi-novel/userrpc/internal/svc"
	"shuqi-novel/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册
func (l *RegisterLogic) Register(in *userrpc.RegisterRequest) (*userrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.Login(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if user.ID != 0 {
		return nil, errors.New("该手机号已注册")
	}

	user = mysql.User{
		Mobile:   in.Mobile,
		Password: in.Password,
	}
	err = user.Register(mysql.DB)
	if err != nil {
		return nil, errors.New("注册失败")
	}
	return &userrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
